<template>
  <div class="content">
   
   
     <!-- 面包屑 -->
     <div class="mianbao">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/pagesContent' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item replace :to="{ path: '/goodDetail?type='+this.type }">保险详情</el-breadcrumb-item>
        <el-breadcrumb-item>{{title}}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>套餐内容</span>
      </div>
      <div class="row1">
        <div class="zuo">
          电梯责任保险
        </div>
        <div class="you">
          <div class="qian" v-if="type==1">
            110元/部
          </div>
          <div class="qian" v-if="type==2">
            350元/部
          </div>
          <div class="qian" v-if="type==3">
            450元/部
          </div>
        </div>
      </div>
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>投保人信息</span>
      </div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="180px" class="demo-ruleForm">
        <el-form-item label="投保人(公司名称)" prop="insureName">
          <el-input v-model="ruleForm.insureName" placeholder="请输入投保人(公司名称)"></el-input>
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="insureCode">
         <el-input v-model="ruleForm.insureCode" placeholder="请输入统一社会信用代码"></el-input>
        </el-form-item>
        <el-form-item label="投保人联系电话" prop="insureMobile">
          <el-input v-model="ruleForm.insureMobile" placeholder="请输入投保人联系电话"></el-input>
        </el-form-item>
        <el-form-item label="投保人地址" prop="insureAddress">
         <el-input v-model="ruleForm.insureAddress" placeholder="请输入投保人地址"></el-input>
        </el-form-item>
        <el-form-item prop="sTime" label="投保时间">
          <el-date-picker type="datetime" placeholder="选择日期"  value-format="yyyy-MM-dd HH:mm:ss" v-model="ruleForm.sTime" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="投保人被保人信息一致" prop="desc">
           <el-checkbox v-model="checked">投保人被保人信息一致</el-checkbox>
        </el-form-item>
        <el-form-item label="被保人(公司名称)" prop="insuredName">
          <el-input v-model="ruleForm.insuredName" placeholder="请输入被保人(公司名称)"></el-input>
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="insuredCode">
         <el-input v-model="ruleForm.insuredCode" placeholder="请输入统一社会信用代码"></el-input>
        </el-form-item>
        <el-form-item label="被保人地址" prop="insuredAddress">
         <el-input v-model="ruleForm.insuredAddress" placeholder="请输入被保人地址"></el-input>
        </el-form-item>
        <el-form-item label="电梯座落地址" prop="insuredLiftAddress">
          <el-input v-model="ruleForm.insuredLiftAddress" placeholder="请输入电梯座落地址"></el-input>
        </el-form-item>
        <el-form-item label="营业执照" prop="insuredBusinessLicense">
          <el-upload
            class="upload-demo"
            :action="qiniuUrl"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            :data="upData"
            :limit="1"
            :file-list="fileList"
            :multiple="false"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2m</div>
          </el-upload>
        </el-form-item>
        
      </el-form>
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>电梯信息</span>
         <el-button style="float: right; padding: 3px 0" @click="addele" type="text">新增电梯</el-button>
      </div>
      <div class="dtbox" v-for="(item,index) of elevatorList" @click="goeledetail(item)" :key="index">
        <div class="row1">
          <div class="zuo">
            电梯编号
          </div>
          <div class="you">
            {{ item.liftNum }}
          </div>
        </div>
        <div class="btnrow">
          <el-button type="primary" size="small" @click.stop="edit(item)">编辑</el-button>
          <el-button type="danger" size="small" @click.stop="del(index)">删除</el-button>
        </div>
      </div>
      
    </el-card>
    <div class="dabtn">
      <el-button type="info" class="btn" @click="submitForm(0)">保存草稿</el-button>
      <el-button type="primary" class="btn" @click="submitForm(1)">立即提交</el-button>
    </div>
    <el-dialog
      title="新增电梯"
      :visible.sync="dialogVisible"
      width="600px"
      >
      <el-autocomplete
      style="width: 100%;"
        v-model="liftNum"
        :fetch-suggestions="querySearchAsync"
        placeholder="请输入电梯编号"
        @select="handleSelect"
      ></el-autocomplete>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="makeit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { addbx,editbx,bxdetail,qiniutoken,getelevatorlist } from "@/api/bx.js"
export default {
  name: "goodDetail",//个人中心 
  data() {
    return {
      loading: false, // 加载状态
      type:0,
      checked:false,
      elevatorList:[],
      title:"电梯责任保险投保",
      fileList:[],
      info:{},
      ruleForm: {},
      rules: {
          insureName: [
            { required: true, message: '请输入投保人(公司名称)', trigger: 'blur' },
            { min: 4, max: 30, message: '长度在 4 到 30 个字符', trigger: 'blur' }
          ],
          insureCode: [
            { required: true, message: '投保人统一社会信用代码不能为空', trigger: 'change' }
          ],
          insureMobile: [
            { required: true, message: '投保人联系电话不能为空', trigger: 'blur' }
          ],
          insureAddress: [
            { required: true, message: '投保人地址不能为空', trigger: 'blur' }
          ],
          sTime: [
            { required: true, message: '投保时间不能为空', trigger: 'change' }
          ],
          insuredName: [
            { required: true, message: '请输入被保人(公司名称)', trigger: 'blur' },
            { min: 4, max: 30, message: '长度在 4 到 30 个字符', trigger: 'blur' }
          ],
          insuredCode: [
            { required: true, message: '被保人统一社会信用代码不能为空', trigger: 'change' }
          ],
          insuredAddress: [
            { required: true, message: '被保人地址不能为空', trigger: 'blur' }
          ],
          insuredLiftAddress: [
            { required: true, message: '电梯座落地址不能为空', trigger: 'blur' }
          ],
          insuredBusinessLicense: [
            { required: true, message: '营业执照不能为空', trigger: 'change' }
          ]
        },
        goback:false,
        liftNum:'',
        dialogVisible:false,
        qiniuUrl:'',
        realmName:'',
        upData:{
          token: '',
          key: '',
          bucket: "tiyulife",
        },
        eleObj:{
          liftNum: '', //电梯注册代码
          liftBrand: '', //品牌型号
          liftPermit: '', //《电梯准用证》号码
          liftPeriod: '', //《电梯准用证》有效期
          liftSpeed: '', //运行速度
          liftUseTime: '', //投入使用时间 格式:yyyy-MM或yyy/MM
          hasProfessional: 1, //有无专职管理人员 1:有 2:无
          weight: '', //载重量 单位同定“kg"
          natureOfUse: '', //电梯所在建筑物使用性质
          permitCertificateImg: '', //电梯准用证图片
          conformityCertificateImg: '' //电梯合格证图片
        }
    };
  },
  watch:{
    
    goback(){
      if(this.goback){
        this.$router.push({path:"/pagesContent",query:{go:2} })
      }
    },
    checked(val){
      if(val){
        this.ruleForm.insureName?this.ruleForm.insuredName = this.ruleForm.insureName:''
        this.ruleForm.insureCode?this.ruleForm.insuredCode = this.ruleForm.insureCode:''
        this.ruleForm.insureAddress?this.ruleForm.insuredAddress = this.ruleForm.insureAddress:''
      }else{
        this.ruleForm.insuredName = ''
        this.ruleForm.insuredCode = ''
        this.ruleForm.insuredAddress = ''
      }
    },
    
    
  },
  created(){
    var type=this.$route.query.type
    this.type=type
    var id=this.$route.query.id
    if(id){
      this.getdetail(id)
    }
    
  },
  mounted() {
    this.getToken()
    this.qiniuUrl = this.$qiniuUrl
    this.realmName = this.$realmName
    var ruleForm=sessionStorage.getItem('ruleForm')
    var checked=sessionStorage.getItem('checked')
    if(checked){
      this.checked=JSON.parse(checked)
      sessionStorage.removeItem('checked')
    }
    if(ruleForm){
      this.ruleForm=JSON.parse(ruleForm)
      sessionStorage.removeItem('ruleForm')
      if(this.ruleForm.insuredBusinessLicense){

        this.fileList=[]
        this.fileList.push({
          name: '营业执照',
          url: this.ruleForm.insuredBusinessLicense
        })
      }
    }
     var eleobj=sessionStorage.getItem('eleobj')
     var elevatorList=sessionStorage.getItem('elevatorList')
     if(eleobj){
      var ele=JSON.parse(eleobj)
      this.elevatorList=JSON.parse(elevatorList)
      console.log(this.elevatorList)
      this.elevatorList.splice(this.elevatorList.findIndex(item=>item.liftNum==ele.liftNum),1,ele)
      sessionStorage.removeItem('eleobj')
      sessionStorage.removeItem('elevatorList')
     }
  },
  
  methods: {
     getdetail(id){
      bxdetail(id).then(res=>{
        console.log(res)
        this.info=res.data
        this.ruleForm=res.data.insuranceOrderUserInfo
        this.elevatorList=res.data.insuranceOrderLiftList
        this.$set(this.ruleForm,'sTime',res.data.sTime)
        if(this.ruleForm.insuredBusinessLicense){
          this.fileList=[]
          this.fileList.push({
            name: '营业执照',
            url: this.ruleForm.insuredBusinessLicense
          })
        }
      })
    },
    async querySearchAsync(queryString, cb) {
      var form=sessionStorage.getItem('form')
      if(form&&form=='dt'){
        const res =await getelevatorlist({
          registerCode:queryString
        })
        console.log(res)
        let results = [];
        if(res.data&&res.data.length>0){
          res.data.forEach((item) => {
            results.push({
              value: item.registerCode+'('+item.buildingName+')',
              ...item
            });
        })
        }
        cb(results);
      }else{
        cb([])
      }

     
    },
    handleSelect(item) {
      console.log(item);
      this.eleObj={
        liftNum: item.registerCode,
        liftBrand: item.brand,
        liftPermit: '',
        liftPeriod: '',
        liftSpeed: item.retedSpeed.replace('M/S',''),
        liftUseTime: item.startRunTime.slice(0, 7),
        hasProfessional: 1,
        weight: item.retedLoad.replace('KG',''),
        natureOfUse: '',
        permitCertificateImg: '',
        conformityCertificateImg: '',
      }
    },
    //获取七牛token
    getToken() {
      qiniutoken().then(res => {
        // console.log(res)
        this.upData.token = res.msg
      })
    },
    ...mapActions(['changeeleObj']),
    goeledetail(){
       sessionStorage.setItem('ruleForm',JSON.stringify(this.ruleForm))
      sessionStorage.setItem('elevatorList',JSON.stringify(this.elevatorList))
      sessionStorage.setItem('checked',this.checked)
      this.changeeleObj(item)
      this.$router.push({path:"/eleAdd",query:{type:3} })
    },
    edit(item){
      sessionStorage.setItem('ruleForm',JSON.stringify(this.ruleForm))
      sessionStorage.setItem('elevatorList',JSON.stringify(this.elevatorList))
      sessionStorage.setItem('checked',this.checked)
      this.changeeleObj(item)
      this.$router.push({path:"/eleAdd",query:{type:2} })
    },
    del(index){
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.elevatorList.splice(index,1)
      });
    },
    async makeit(){
      if(!this.liftNum){
        return this.$message.error('请输入电梯注册代码')
      }
      if(this.elevatorList&&this.elevatorList.length>0){
        var ar=this.elevatorList.filter(item=>item.liftNum==this.liftNum)
        console.log(ar)
        if(ar.length>0){
          return this.$message.error('此电梯注册代码已登记。')
        }
      }
      if(this.eleObj.liftNum.indexOf('(')>-1){
        this.eleObj.liftNum=this.eleObj.liftNum.split('(')[0]
      }
      if(!this.eleObj.liftBrand){
        this.$set(this.eleObj,'liftNum',this.liftNum)
      }
      this.elevatorList.push(this.eleObj)
      this.dialogVisible=false
      this.changeeleObj(this.eleObj)
      sessionStorage.setItem('ruleForm',JSON.stringify(this.ruleForm))
      sessionStorage.setItem('elevatorList',JSON.stringify(this.elevatorList))
      sessionStorage.setItem('checked',this.checked)
      this.$router.push({path:"/eleAdd",query:{type:1,qiantype:this.type} })

    },
    addele(){
     
      if(this.elevatorList&&this.elevatorList.length==5){
        return this.$message.error('最多添加5个电梯')
      }

      this.liftNum=''
      this.dialogVisible=true
    },
    submitForm(num) {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if(!this.elevatorList||this.elevatorList.length==0){
						return this.$message.error('请添加电梯')
					}
					var strarr=[]
					this.elevatorList.map(item=>{
						if(!item.liftBrand){
							strarr.push('电梯信息不完整，请完善电梯信息')
						}
					})
					if(strarr.length>0){
						return this.$message.error(strarr[0])
					}
          this.info.productId=1
					this.info.planId=this.type
					this.info.orderStatus=num
          this.info.sTime=this.ruleForm.sTime
          this.info.insuranceOrderUserInfo={
						"codeType": 9, //社会同意信用代码 写死
						"insureName": this.ruleForm.insureName, //投保人姓名
						"insureCode":this.ruleForm.insureCode,  //投保人证件号
						"insureMobile": this.ruleForm.insureMobile, //投保人联系电话
						"insureAddress": this.ruleForm.insureAddress, //投保人地址
						"insuredName": this.ruleForm.insuredName, //被保人姓名
						"insuredCode":this.ruleForm.insuredCode, //被保人证件号
						"insuredAddress": this.ruleForm.insuredAddress, //被保人地址
						"insuredLiftAddress": this.ruleForm.insuredLiftAddress, //电梯座落地址
						"insuredBusinessLicense": this.ruleForm.insuredBusinessLicense //营业执照图片
					}
          this.info.insuranceOrderLiftList=this.elevatorList
          if(this.info.id){
            const res1 =await editbx(this.info)
            console.log(res1)
            if(res1.code!=200){
              return this.$message.error(res1.msg)
            }
            if(num==0){
              this.$router.push({path:"/pagesContent",query:{go:2}})
            }else{
              this.goback=true
              window.location.href = res1.msg
            }
            
          }else{
            const res1 =await addbx(this.info)
            console.log(res1)
            if(res1.code!=200){
              return this.$message.error(res1.msg)
            }
            if(num==0){
              this.$router.push({path:"/pagesContent",query:{go:2}})
            }else{
              this.goback=true
              window.location.href = res1.msg
            }
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    beforeUpload(file) {
      console.log(file)
      var now=new Date().getTime()
      this.upData.key= now +'-'+ file.name
      // const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      // if (!isJPG) {
      //   this.$message.error('上传图片只能是 JPG/PNG 格式!')
      // }
      // return isJPG
    },
    handleSuccess(res, file){
      console.log(res, file);

      this.ruleForm.insuredBusinessLicense=this.realmName + res.key;
    },
     handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      }
  },
  
};
</script>
<style scoped lang="scss">
.content{
  padding-bottom: 45px;
  background: #fff;
  .mianbao{
    max-width: 1200px;
    margin:0  auto 16px;
    padding-top: 20px;
  }
  .box-card{
    max-width: 1200px;
    margin: 25px auto 30px;
    .dtbox{
      border-bottom: 1px solid #ccc;
      padding-bottom: 20px;
      margin-bottom: 20px;
      .btnrow{
        display: flex;
        justify-content: flex-end;
      }
    }
    
    .row1{
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 20px;
      .zuo{
        font-size: 16px;
        color: #333333;
      }
      .you{
        font-size: 16px;
        color: #999999;
        .qian{
          color: #165DFF;
          font-weight: bold;
        }
      }
    }
    .neirong{
      width: 100%;
      height: fit-content;
      padding: 16px;
      box-sizing: border-box;
      background: rgba(22, 93, 255, .1);
      border-radius: 8px;
      font-weight: 400;
      font-size: 14px;
      color: #165DFF;
      line-height: 27px;
      text-indent: 2rem;
      margin-bottom: 20px;
    }
  }
  .dabtn{
    max-width: 1200px;
    margin: 30px auto;
    display: flex;
    justify-content: center;
    align-items: center;
    .btn{
      width: 40%;
      height: 80px;
      margin: 30px auto;
      display: block;
      font-size: 40px;
      margin-right: 40px;
    }
  }
  

}
</style>
